<template>
  <div class="app-main-content-box">
    <!--filter区域-->
    <div class="filter-content">
      <el-form
        ref="filterForm"
        :model="filterForm"
        label-width="110px"
        size="small"
      >
        <div class="flexRSS">
          <div>
            <el-form-item
              :rules="[{ required: true, message: '时间区间不能为空' }]"
              label="核销时间："
              prop="date"
            >
              <el-date-picker
                v-model="filterForm.date"
                :default-time="['00:00:00', '23:59:59']"
                type="datetimerange"
                range-separator="~"
                value-format="yyyy-MM-dd HH:mm:ss"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </el-form-item>
            <el-form-item
              label="券码："
              prop="couponCode"
            ><el-input
              v-model="filterForm.couponCode"
              style="width: 400px"
              placeholder="请输入"
            /></el-form-item>
            <el-form-item
              label="订单号："
              prop="orderNo"
            ><el-input
              v-model="filterForm.orderNo"
              style="width: 400px"
              placeholder="请输入"
            /></el-form-item>
            <!--<el-form-item-->
            <!--  prop="shopId"-->
            <!--  label="核销门店：">-->
            <!--  <el-select-->
            <!--    v-model="filterForm.shopId"-->
            <!--    filterable-->
            <!--    placeholder="可通过名称搜索"-->
            <!--    style="width: 400px">-->
            <!--    <el-option-->
            <!--      label="所有门店"-->
            <!--      value/>-->
            <!--    <el-option-->
            <!--      v-for="(item, index) in manageShopList"-->
            <!--      :key="index"-->
            <!--      :label="item.name"-->
            <!--      :value="item.id"/>-->
            <!--  </el-select>-->
            <!--</el-form-item>-->
            <el-form-item label="核销方：" prop="merchant">
              <el-cascader
                v-model="filterForm.merchantArr"
                :options="[{ id: '', name: '所有' }].concat(allAuthMchOptions)"
                :props="{
                  checkStrictly: true,
                  value: 'id',
                  label: 'name',
                  children: 'shops',
                }"
                style="width: 400px"
                clearable
              />
            </el-form-item>
            <el-form-item label="核销订单号：" prop="transactionId">
              <el-input
                v-model="filterForm.transactionId"
                style="width: 400px"
                placeholder="请输入"
              />
            </el-form-item>

            <el-form-item label="顾客手机：" prop="customerPhone">
              <el-input
                v-model="filterForm.customerPhone"
                style="width: 400px"
                placeholder="请输入"
              />
            </el-form-item>
          </div>
          <div>
            <el-form-item label="核销业务：" prop="bizCode">
              <el-select
                v-model="filterForm.bizCode"
                filterable
                placeholder="请选择"
                style="width: 400px"
              >
                <el-option label="所有" value="" />
                <el-option
                  v-for="(item, index) in manageBizCodeOptions"
                  :key="index"
                  :label="item.label"
                  :value="item.key"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="核销来源：" prop="sourceCode">
              <el-select
                v-model="filterForm.sourceCode"
                filterable
                placeholder="请选择"
                style="width: 400px"
              >
                <el-option label="所有" value="" />
                <el-option
                  v-for="(item, index) in sourceCodeOptions"
                  :key="index"
                  :label="item.label"
                  :value="item.key"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="核销终端：" prop="endpoint">
              <el-input
                v-model="filterForm.endpoint"
                style="width: 400px"
                maxlength="40"
                placeholder="请输入"
              />
              <!--<el-select-->
              <!--  v-model="filterForm.endpoint"-->
              <!--  filterable-->
              <!--  placeholder="可通过终端名/终端编号搜索"-->
              <!--  style="width:400px"-->
              <!--&gt;-->
              <!--  <template v-for="item in $store.state.user.allManageDeviceFilterOptions">-->
              <!--    <el-option-->
              <!--      v-if="filterForm.shopId === '' ||item.shopId === filterForm.shopId || item.kdDeviceNo ===''"-->
              <!--      :key="item.id"-->
              <!--      :label="-->
              <!--        item.kdDeviceNo === ''-->
              <!--          ? item.deviceName-->
              <!--          : item.deviceName + '(' + item.kdDeviceNo + ')'-->
              <!--      "-->
              <!--      :value="item.kdDeviceNo"-->
              <!--    />-->
              <!--  </template>-->
              <!--</el-select>-->
              <!--<el-input v-model="filterForm.endpoint" style="width:400px" maxlength="40" placeholder="请输入"/>-->
              <!--              <el-select v-model="filterForm.endpoint" filterable placeholder="可通过终端名/终端编号搜索" style="width: 400px">-->
              <!--                <template-->
              <!--                  v-for="item in $store.state.user-->
              <!--                  .allManageDeviceFilterOptions">-->
              <!--                  <el-option-->
              <!--                    v-if="-->
              <!--                      filterForm.shopId === '' ||-->
              <!--                        item.shopId == filterForm.shopId ||-->
              <!--                        item.kdDeviceNo == ''-->
              <!--                    "-->
              <!--                    :key="item.id"-->
              <!--                    :label="-->
              <!--                      item.kdDeviceNo === ''-->
              <!--                        ? item.deviceName-->
              <!--                        : item.deviceName + '(' + item.kdDeviceNo + ')'-->
              <!--                    "-->
              <!--                    :value="item.kdDeviceNo"/>-->
              <!--                </template>-->
              <!--              </el-select>-->
            </el-form-item>
            <el-form-item label="核销商户号：" prop="consumeMchid">
              <el-input
                v-model="filterForm.consumeMchid"
                style="width: 400px"
                placeholder="请输入"
              />
            </el-form-item>
            <el-form-item
              label="顾客："
              prop="customerName"
            ><el-input
              v-model="filterForm.customerName"
              style="width: 400px"
              placeholder="请输入"
            /></el-form-item>
          </div>
        </div>

        <el-form-item class="filter-btn">
          <el-button type="primary" round @click="submitForm">查 询</el-button>
          <el-button round @click="resetForm">重 置</el-button>
          <el-button round @click="downExcel">导 出</el-button>
        </el-form-item>
      </el-form>
    </div>

    <AppTableStatisticsCard :statistics-card-data="statisticsCardData" />

    <div class="table-content">
      <el-table
        :data="list"
        size="small"
        border
        stripe
        style="width: 100%"
        empty-text="暂无数据"
      >
        <el-table-column
          prop="scope.row.couponCodes"
          label="核销流水号/时间"
          fixed="left"
        >
          <template slot="header" slot-scope="scope">
            <div>核销流水号</div>
            <div>时间</div>
          </template>
          <template slot-scope="scope">
            <span>{{ scope.row.serialNo }}</span>
            <span>{{ scope.row.createTime }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="couponCodes" label="券码">
          <template slot-scope="scope">
            <span>{{ scope.row.couponCodes.join("、") }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="couponCode" label="数量">
          <template slot-scope="scope">
            <span>{{ scope.row.couponCodes.length }}</span>
          </template>
        </el-table-column>
        <el-table-column label="核销方/核销门店/核销人/核销终端">
          <template slot="header" slot-scope="scope">
            <div>核销方 / 核销门店 / 核销人</div>
            <div>核销终端</div>
          </template>
          <template slot-scope="scope">
            <div>
              {{
                (scope.row.merchantName || "无") +
                  " / " +
                  (scope.row.shopName || "无") +
                  " / " +
                  (scope.row.operatorName || "无")
              }}
            </div>
            <div>{{ scope.row.endpoint || "无" }}</div>
          </template>
        </el-table-column>
        <!--        <el-table-column label="核销业务/核销来源/业务订单号">-->
        <el-table-column label="核销业务/核销来源">
          <template slot="header" slot-scope="scope">
            <div>核销业务 / 核销来源</div>
            <!--            <div>业务订单号</div>-->
          </template>
          <template slot-scope="scope">
            <span>{{
              (bizCodeKeyOptions[scope.row.bizCode] || "无") +
                " / " +
                (sourceCodeKeyOptions[scope.row.sourceCode] || "无")
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="customerName" label="顾客：">
          <template slot-scope="scope">
            <div>
              {{ scope.row.customerName
              }}{{
                scope.row.customerPhone ? `(${scope.row.customerPhone})` : ""
              }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="consumeMchid" label="核销商户号" />
        <el-table-column prop="orderNo" label="核销订单号" />
        <el-table-column prop="remark" label="备注" />
      </el-table>
      <!-- 分页 -->
      <pagination-direction
        v-if="paginationConfig.total !== 0"
        :config="paginationConfig"
        @sizeschange="sizesChange"
        @pagechange="pageChange"
      />
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { couponVerifyCount, couponVerifyList } from '../../api/coupon'
import { authMerchants } from '../../api/mch'

import { exportCouponVerifyReport } from '@/api/download'
export default {
  props: {
    couponBase: {
      require: true,
      type: Object
    }
  },
  data() {
    return {
      // 配置
      // 分页配置
      paginationConfig: {
        direction: 'center', // 分页位置
        layout: 'total, sizes, prev, pager, next, jumper', // 分页类型
        pageSizes: [10, 20], // 分页pages
        total: 0,
        page: 1, // 页数-默认1
        pageSize: 10 // 每页条数-默认10
      },
      statusOptions: {
        1: '待使用',
        2: '已核销',
        3: '赠送中',
        4: '待使用(锁定中)',
        5: '已过期'
      },
      allAuthMchOptions: [],
      // 状态
      // 数据
      statisticsCardData: [],
      list: [],
      filterForm: {
        date: [
          this.$momentMini().format('YYYY-MM-DD') + ' 00:00:00',
          this.$momentMini().format('YYYY-MM-DD') + ' 23:59:59'
        ],
        start: null,
        end: null,
        couponCode: '',
        bizCode: '',
        sourceCode: '',
        couponId: '',
        endpoint: '',
        merchantArr: [''],
        orderNo: '',
        shopId: '',
        consumeMchid: null,
        transactionId: null
      }
    }
  },
  computed: {
    ...mapGetters([
      'manageShopList',
      'manageBizCodeOptions',
      'bizCodeKeyOptions',
      'sourceCodeOptions',
      'sourceCodeKeyOptions',
      'userInfo'
    ])
  },
  watch: {
    'filterForm.shopId'() {
      this.filterForm.endpoint = ''
    }
  },
  created() {},
  mounted() {
    this.getAuthMerchants()
    this.fetchData()
  },
  methods: {
    /**
     * 数据组
     */
    fetchData(
      page = this.paginationConfig.page,
      pageSize = this.paginationConfig.pageSize
    ) {
      this.$refs.filterForm.validate((valid) => {
        if (valid) {
          const params = this.fetchFilterParams()
          params.page = page
          params.pageSize = pageSize
          this.loading = true
          Promise.all([this.getList(params), this.getCount(params)]).then(
            (res) => {
              this.loading = false
            }
          )
        }
      })
    },

    // 获取列表
    getList(params) {
      return new Promise((resolve, reject) => {
        couponVerifyList(params)
          .then((res) => {
            this.list = res.data.list
            this.paginationConfig.total = res.data.total
            this.paginationConfig.page = res.data.pageNum
          })
          .finally(() => {
            resolve()
          })
      })
    },

    // 获取统计
    getCount(params) {
      return new Promise((resolve, reject) => {
        if (params.page !== 1) {
          resolve()
        } else {
          this.statisticsCardData = [
            {
              title: '核销数 / 张',
              value: 0,
              describeList: [],
              detailList: []
            }
          ]
          couponVerifyCount(params)
            .then((res) => {
              this.statisticsCardData[0].value =
                res.data && res.data.couponNum ? res.data.couponNum : 0
            })
            .finally(() => {
              resolve()
            })
        }
      })
    },

    fetchFilterParams() {
      let params = {}
      params = Object.assign({}, this.filterForm)
      params.start = params.date[0]
      params.end = params.date[1]
      params.couponId = this.couponBase.id
      if (params.merchantArr) {
        if (params.merchantArr.length == 1 && params.merchantArr[0] !== '') {
          params.merchant = params.merchantArr[0]
          params.shopId =
            !this.userInfo.isAdmin &&
            params.merchantArr[0] == this.userInfo.business.id
              ? this.userInfo.shopId
              : ''
        } else if (params.merchantArr.length == 2) {
          params.merchant = params.merchantArr[0]
          params.shopId = params.merchantArr[1]
        } else {
          params.merchant = this.userInfo.isAdmin
            ? ''
            : this.userInfo.business.id
          params.shopId = this.userInfo.isAdmin ? '' : this.userInfo.shopId
        }
      }
      delete params.date
      delete params.merchantArr
      // 清除多余字段
      for (const key in params) {
        if (params[key] === '' || params[key] === 'all') {
          delete params[key]
        }
      }
      return params
    },
    // 获取合作商户
    getAuthMerchants() {
      const { id } = this.userInfo.business
      const { isAdmin, shopId } = this.userInfo
      return new Promise((resolve) => {
        authMerchants({ belongMerchant: this.couponBase.belongMerchant })
          .then((res) => {
            if (!isAdmin) {
              // 删除不属于本商户的门店
              for (let i = 0; i < res.data.length; i++) {
                if (res.data[i].id == id) {
                  const shops = res.data[i].shops
                  for (let k = 0; k < shops.length; k++) {
                    if (shops[k].id != shopId) {
                      delete shops[k]
                    }
                  }
                }
              }
              this.allAuthMchOptions = res.data
            } else {
              this.allAuthMchOptions = res.data
            }
          })
          .finally(() => {
            resolve()
          })
      })
    },
    /**
     * 按钮组
     */
    // 分页sizes改变
    sizesChange() {
      this.fetchData()
    },

    // 分页page改变
    pageChange() {
      this.fetchData()
    },

    // 查询
    submitForm() {
      this.fetchData(1)
    },

    // 导出
    downExcel() {
      const data = this.fetchFilterParams()
      exportCouponVerifyReport(data).then((res) => {
        if (res.code === 0) {
          this.$alert('数据导出中，请稍后到数据下载中心进行下载', '提示', {
            confirmButtonText: '确定',
            center: true,
            type: 'success'
          })
        }
      })
    },
    // 重置
    resetForm() {
      this.$refs.filterForm.resetFields()
    }
    /**
     * 状态组
     */
    /**
     * 方法组
     */
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
/* 筛选 */
.filter-container {
  .filter-btn {
    margin-bottom: 20px;
  }

  .check-all {
    margin-right: 30px;
  }

  // 单选换行
  .el-radio + .el-radio {
    margin-left: 0;
  }

  .el-radio {
    margin-right: 10px;
    height: 32px;
    line-height: 32px;
  }
}

/* 表格 */
.table-content {
  margin-top: 10px;
}
</style>
